package pers.corvey.exam.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import pers.corvey.exam.controller.common.BaseControllerImpl;
import pers.corvey.exam.entity.ExamPaper;
import pers.corvey.exam.entity.Question;
import pers.corvey.exam.helper.form.QuestionFormHelper;
import pers.corvey.exam.service.ExamPaperService;
import pers.corvey.exam.service.QuestionService;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/question")
public class QuestionController extends BaseControllerImpl<Question, Long> {

	private static String UPLOADPATH="D:/image/";

	private final QuestionService questionService;
	private final ExamPaperService examPaperService;
	
	@Autowired
	public QuestionController(QuestionService service, ExamPaperService examPaperService) {
		super(service, "question-input.jsp", "question-list.jsp");
		this.questionService = service;
		this.examPaperService = examPaperService;
	}

	@PostMapping(SAVE_PATH)
	public String save(Model model, 
			@ModelAttribute(ENTITY_ATTRIBUTE_NAME) Question question,
			QuestionFormHelper questionFormHelper,@RequestParam("file") MultipartFile file) throws IOException {
		//后缀名  如 .txt
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		//后缀名之前的名称
		String prefix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
		DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
		// 将此时时间转换为字符串
		String formatDate = format.format(new Date());
		// 拼接文件名
		String filename = new StringBuffer().append(prefix).append("_").append(formatDate).append(suffix).toString();
		Path path = Paths.get(UPLOADPATH + File.separator +filename);
		String url = "/" +filename;
		//如果没有此文件夹，则创建
		if (!Files.isWritable(path)) {
			Files.createDirectories(Paths.get(UPLOADPATH));
		}
		//文件写入指定路径
		Files.write(path,  file.getBytes());
		questionFormHelper.updateToQuestion(question);
		question.setImgurl(url);
		return baseSave(question);
	}

	@RequestMapping("/getImage")
	@ResponseBody
	public void getImage(String filePath, HttpServletResponse rp) {
		File imageFile = new File(UPLOADPATH+filePath);
		if (imageFile.exists()) {
			FileInputStream fis = null;
			OutputStream os = null;
			try {
				fis = new FileInputStream(imageFile);
				os = rp.getOutputStream();
				int count = 0;
				byte[] buffer = new byte[1024 * 8];
				while ((count = fis.read(buffer)) != -1) {
					os.write(buffer, 0, count);
					os.flush();
				}

			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					fis.close();
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	@Override
	public String showInputView(Model model, 
			@ModelAttribute(ENTITY_ATTRIBUTE_NAME) Question entity) {
		
		Iterable<ExamPaper> exampapers = examPaperService.findAll();
		model.addAttribute("exampapers", exampapers);
		return super.showInputView(model, entity);
	}
	
	@Override
	public String showDetailView(Model model, 
			@ModelAttribute(ENTITY_ATTRIBUTE_NAME) Question entity) {
		
		Iterable<ExamPaper> exampapers = examPaperService.findAll();
		model.addAttribute("exampapers", exampapers);
		return super.showDetailView(model, entity);
	}
	
	@RequestMapping("/{questionId}")
	public String show(Model model, @PathVariable Long questionId) {
		Question question = questionService.findByID(questionId);
		model.addAttribute("question", question);
		return "question-show";
	}
}
